package com.ruoyi.ftrl.service.impl;

import java.io.IOException;
import java.math.BigDecimal;
import java.text.DateFormat;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.*;
import java.util.concurrent.*;

import com.fasterxml.jackson.databind.JsonNode;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.ruoyi.common.core.redis.RedisCache;
import com.ruoyi.common.exception.ServiceException;
import com.ruoyi.common.utils.DateUtils;
import com.ruoyi.common.utils.SecurityUtils;
import com.ruoyi.ftrl.domain.*;
import com.ruoyi.ftrl.domain.Dto.AutoSendDto;
import com.ruoyi.ftrl.domain.Dto.HandSendDto;
import com.ruoyi.ftrl.mapper.*;
import com.ruoyi.ftrl.service.MessagePublisher;
import com.ruoyi.ftrl.service.RedisMessageHandlers;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.http.*;
import org.springframework.stereotype.Service;
import com.ruoyi.ftrl.service.IControlValveService;
import org.springframework.web.client.RestTemplate;

import java.util.concurrent.CompletableFuture;

/**
 * 温控阀采集数据Service业务层处理
 * 
 * @author dihang
 * @date 2024-08-08
 */
@Service
public class ControlValveServiceImpl implements IControlValveService
{
    @Autowired
    private ControlValveMapper controlValveMapper;
    @Autowired
    //Redis工具类
    RedisCache redisCache;
    @Autowired
    private ControlRecordsMapper controlRecordsMapper;
    @Autowired
    private HeatInfoMapper heatInfoMapper;
    @Autowired
    private EquipmentDockingMapper equipmentDockingMapper;

    /**
     * 查询温控阀采集数据
     * 
     * @param id 温控阀采集数据主键
     * @return 温控阀采集数据
     */
    @Override
    public ControlValve selectControlValveById(Long id)
    {
        return controlValveMapper.selectControlValveById(id);
    }

    /**
     * 查询温控阀采集数据列表
     * 
     * @param controlValve 温控阀采集数据
     * @return 温控阀采集数据
     */
    @Override
    public List<ControlValve> selectControlValveList(ControlValve controlValve)
    {
        List<ControlValve> controlValves = controlValveMapper.selectControlValveList(controlValve);
        for (ControlValve controlValf : controlValves) {
            //温差 Field2
            String cha=String.valueOf(Double.parseDouble(controlValf.getIntemp())-Double.parseDouble(controlValf.getOuttemp()));
            controlValf.setField2(cha);
        }
        return controlValves;

    }

    /**
     * 新增温控阀采集数据
     * 
     * @param controlValve 温控阀采集数据
     * @return 结果
     */
    @Override
    public int insertControlValve(ControlValve controlValve)
    {
        controlValve.setCreateTime(DateUtils.getNowDate());
        return controlValveMapper.insertControlValve(controlValve);
    }

    /**
     * 修改温控阀采集数据
     * 
     * @param controlValve 温控阀采集数据
     * @return 结果
     */
    @Override
    public int updateControlValve(ControlValve controlValve)
    {
        controlValve.setUpdateTime(DateUtils.getNowDate());
        return controlValveMapper.updateControlValve(controlValve);
    }

    /**
     * 批量删除温控阀采集数据
     * 
     * @param ids 需要删除的温控阀采集数据主键
     * @return 结果
     */
    @Override
    public int deleteControlValveByIds(Long[] ids)
    {
        return controlValveMapper.deleteControlValveByIds(ids);
    }

    /**
     * 删除温控阀采集数据信息
     * 
     * @param id 温控阀采集数据主键
     * @return 结果
     */
    @Override
    public int deleteControlValveById(Long id)
    {
        return controlValveMapper.deleteControlValveById(id);
    }

    private final StringRedisTemplate redisTemplate;

    public ControlValveServiceImpl(StringRedisTemplate redisTemplate) {
        this.redisTemplate = redisTemplate;
    }

    public void publish(String message) {
        redisTemplate.convertAndSend("students", message);
    }

    public void heartbeat(){
        String string="heartbeat";
        publish(string);
    }

    /**
     * 温控阀发送控制指令
     */
    @Autowired
    private ControlValveMapper ctrlValveMapper;
    @Autowired
            private RoomInfoMapper roomInfoMapper;
    MessagePublisher messagePublisher;
    @Override
    public int sendConxtrolValve(HandSendDto handSendDto) throws InterruptedException {
        //先将传参编码 对设备进行指令发送
        code(handSendDto);
        //等待回执码并接收 在接收的时候进行异步处理 只要收到了回执码 就对回执码返回的数据进行逻辑处理 也就是将回执码返回的成功失败状态进行在操作记录上的赋值
        //在等待接收的时候 把这一次的操作记录存入数据库



        //接受传过来的参数 将操作的设备指令入库
        List<String> roomNos = handSendDto.getRoomNo();
        String type = handSendDto.getType();
        //开关阀操作
        if (type.equals("0")||type.equals("1")||type.equals("2")||type.equals("3")){
            for (String roomNo : roomNos) {

                ControlRecords controlRecords = new ControlRecords();
                RoomInfo roomInfo = roomInfoMapper.selectRoomInfoByRoomNo(roomNo);
                //锁闭阀
                ControlValve controlValve = ctrlValveMapper.selectControlValveByRoomNoLock(roomNo);
                //流量阀
                ControlValve controlValve2 = ctrlValveMapper.selectControlValveByRoomNoFlow(roomNo);
                if (controlValve != null) {
                    //设备ID（计量点ID）
                    controlRecords.setNodeId(controlValve.getMeternum());
                    //所属厂家
                    controlRecords.setManufactor(controlValve.getManufactor());
                    //操作房间
                    controlRecords.setRoom(roomInfo.getCommunityName()+"-"+roomInfo.getBuildingName()+"-"+roomInfo.getUnitName()+"-"+roomInfo.getHouseNumber());
                    //流量阀
                }else if (controlValve2 != null){
                    //设备ID（计量点ID）
                    controlRecords.setNodeId(controlValve2.getMeternum());
                    //所属厂家
                    controlRecords.setManufactor(controlValve2.getManufactor());
                    //操作房间
                    controlRecords.setRoom(roomInfo.getCommunityName()+"-"+roomInfo.getBuildingName()+"-"+roomInfo.getUnitName()+"-"+roomInfo.getHouseNumber());
                }
                else {

                    ControlValve controlValve1 = ctrlValveMapper.selectControlValveByRoomNoUnit(roomNo);
                    if (controlValve1 != null) {
                        //设备ID（计量点ID）
                        controlRecords.setNodeId(controlValve1.getMeternum());
                        //所属厂家
                        controlRecords.setManufactor("0");
                    }else {
                        throw new ServiceException("未检测到该房间或单元下的阀门，无法进行调控！");
                    }
                    //操作房间
                    controlRecords.setRoom(controlValve1.getVillageName()+"-"+controlValve1.getBuildingName()+"-"+controlValve1.getUnitName()+"单元");
                }
                //操作类型
                controlRecords.setType(type);

                //操作内容
                controlRecords.setContent("将设备进行开关阀操作");
                //操作码
                controlRecords.setCode("");
                //操作结果
//                controlRecords.setField1("成功");
                //操作时间
                controlRecords.setCreateTime(new Date());
                //操作人
                controlRecords.setCreateBy(SecurityUtils.getUsername());
                //调控类型
                controlRecords.setField5("0");
                //操作用户ID
                controlRecords.setDeptId(SecurityUtils.getUserId());

                controlRecordsMapper.insertControlRecords(controlRecords);
            }
            //阀门开度设置
        }else if (type.equals("4")){
            for (String roomNo : roomNos) {

                ControlRecords controlRecords = new ControlRecords();
                RoomInfo roomInfo = roomInfoMapper.selectRoomInfoByRoomNo(roomNo);
                //流量阀
                ControlValve controlValve = ctrlValveMapper.selectControlValveByRoomNoFlow(roomNo);
                //锁闭阀
                ControlValve controlValve2 = ctrlValveMapper.selectControlValveByRoomNoLock(roomNo);
                if (controlValve != null) {
                    //设备ID（计量点ID）
                    controlRecords.setNodeId(controlValve.getMeternum());
                    //所属厂家
                    controlRecords.setManufactor(controlValve.getManufactor());
                    //操作房间
                    controlRecords.setRoom(roomInfo.getCommunityName()+"-"+roomInfo.getBuildingName()+"-"+roomInfo.getUnitName()+"-"+roomInfo.getHouseNumber());
                }else if (controlValve2 != null){
                    //设备ID（计量点ID）
                    controlRecords.setNodeId(controlValve2.getMeternum());
                    //所属厂家
                    controlRecords.setManufactor(controlValve2.getManufactor());
                    //操作房间
                    controlRecords.setRoom(roomInfo.getCommunityName()+"-"+roomInfo.getBuildingName()+"-"+roomInfo.getUnitName()+"-"+roomInfo.getHouseNumber());
                }
                else {
                    ControlValve controlValve1 = ctrlValveMapper.selectControlValveByRoomNoUnit(roomNo);
                    if (controlValve1 != null) {
                        //设备ID（计量点ID）
                        controlRecords.setNodeId(controlValve1.getMeternum());
                        //所属厂家
                        controlRecords.setManufactor("0");
                    }else {
                        throw new ServiceException("未检测到该房间或单元下的阀门，无法进行调控！");
                    }
                    //操作房间
                    controlRecords.setRoom(controlValve1.getVillageName()+"-"+controlValve1.getBuildingName()+"-"+controlValve1.getUnitName()+"单元");

                }
                //操作类型
                controlRecords.setType(type);
                //开度值
                controlRecords.setField2(handSendDto.getValue());
                //操作内容
                controlRecords.setContent("将设备进行阀门开度设置操作");
                //操作码
                controlRecords.setCode("");
                //操作结果
//                controlRecords.setField1("成功");
                //操作时间
                controlRecords.setCreateTime(new Date());
                //操作人
                controlRecords.setCreateBy(SecurityUtils.getUsername());
                //调控类型
                controlRecords.setField5("0");
                //操作用户ID
                controlRecords.setDeptId(SecurityUtils.getUserId());
                controlRecordsMapper.insertControlRecords(controlRecords);
            }


            //阀门开度调大
        }else if (type.equals("5")){
            for (String roomNo : roomNos) {

                ControlRecords controlRecords = new ControlRecords();
                RoomInfo roomInfo = roomInfoMapper.selectRoomInfoByRoomNo(roomNo);
                ControlValve controlValve = ctrlValveMapper.selectControlValveByRoomNoFlow(roomNo);
                if (controlValve != null) {
                    //设备ID（计量点ID）
                    controlRecords.setNodeId(controlValve.getMeternum());
                    //所属厂家
                    controlRecords.setManufactor(controlValve.getManufactor());
                    //操作房间
                    controlRecords.setRoom(roomInfo.getCommunityName()+"-"+roomInfo.getBuildingName()+"-"+roomInfo.getUnitName()+"-"+roomInfo.getHouseNumber());
                }else {
                    ControlValve controlValve1 = ctrlValveMapper.selectControlValveByRoomNoUnit(roomNo);
                    if (controlValve1 != null) {
                        //设备ID（计量点ID）
                        controlRecords.setNodeId("01");
                        //所属厂家
                        controlRecords.setManufactor("0");
                    }else {
                        throw new ServiceException("未检测到该房间或单元下的阀门，无法进行调控！");
                    }
                    //操作房间
                    controlRecords.setRoom(controlValve1.getVillageName()+"-"+controlValve1.getBuildingName()+"-"+controlValve1.getUnitName()+"单元");
                    //设备ID（计量点ID）
                    controlRecords.setNodeId("01");
                    //所属厂家
                    controlRecords.setManufactor("0");
                }
                //操作类型
                controlRecords.setType(type);
                //百分比值
                controlRecords.setField3(handSendDto.getBig());

                //操作内容
                controlRecords.setContent("将设备进行阀门开度调大操作");
                //操作码
                controlRecords.setCode("");
                //操作结果
//                controlRecords.setField1("成功");
                //操作时间
                controlRecords.setCreateTime(new Date());
                //操作人
                controlRecords.setCreateBy(SecurityUtils.getUsername());
                //调控类型
                controlRecords.setField5("0");
                //操作用户ID
                controlRecords.setDeptId(SecurityUtils.getUserId());
                controlRecordsMapper.insertControlRecords(controlRecords);
            }

            //阀门开度调小
        }else if (type.equals("6")){
            for (String roomNo : roomNos) {

                ControlRecords controlRecords = new ControlRecords();
                RoomInfo roomInfo = roomInfoMapper.selectRoomInfoByRoomNo(roomNo);
                ControlValve controlValve = ctrlValveMapper.selectControlValveByRoomNoFlow(roomNo);
                if (controlValve != null) {
                    //设备ID（计量点ID）
                    controlRecords.setNodeId(controlValve.getMeternum());
                    //所属厂家
                    controlRecords.setManufactor(controlValve.getManufactor());
                    //操作房间
                    controlRecords.setRoom(roomInfo.getCommunityName()+"-"+roomInfo.getBuildingName()+"-"+roomInfo.getUnitName()+"-"+roomInfo.getHouseNumber());
                }else {
                    ControlValve controlValve1 = ctrlValveMapper.selectControlValveByRoomNoUnit(roomNo);
                    if (controlValve1 != null) {
                        //设备ID（计量点ID）
                        controlRecords.setNodeId("01");
                        //所属厂家
                        controlRecords.setManufactor("0");
                    }else {
                        throw new ServiceException("未检测到该房间或单元下的阀门，无法进行调控！");
                    }
                    //操作房间
                    controlRecords.setRoom(controlValve1.getVillageName()+"-"+controlValve1.getBuildingName()+"-"+controlValve1.getUnitName()+"单元");
                    //设备ID（计量点ID）
                    controlRecords.setNodeId("01");
                    //所属厂家
                    controlRecords.setManufactor("0");
                }
                //操作类型
                controlRecords.setType(type);
                //百分比值
                controlRecords.setField3(handSendDto.getBig());

                //操作内容
                controlRecords.setContent("将设备进行阀门开度调小操作");
                //操作码
                controlRecords.setCode("");
                //操作结果
//                controlRecords.setField1("成功");
                //操作时间
                controlRecords.setCreateTime(new Date());
                //操作人
                controlRecords.setCreateBy(SecurityUtils.getUsername());
                //调控类型
                controlRecords.setField5("0");
                //操作用户ID
                controlRecords.setDeptId(SecurityUtils.getUserId());

                controlRecordsMapper.insertControlRecords(controlRecords);
            }

        }

        return 1;
    }

    // 在类中定义
    private final CompletableFuture<String> futureResponse = new CompletableFuture<>();

    public void completeFuture(String resultCode) {
        futureResponse.complete(resultCode);
    }

//    public CompletableFuture<String> getFutureResponse() {
//        return futureResponse;
//    }
    /**
     * 指令编码 发送到设备
     * @param handSendDto
     */
    public List<String> code(HandSendDto handSendDto) throws InterruptedException {
        //todo 将接受到的前端传参就行编码，存储到redis里
        List<String> results=new ArrayList<>();
        List<String> roomNo = handSendDto.getRoomNo();
        String code = "EB90EB90EB900618";
        //操作类型
        String dtoType = handSendDto.getType();
        //设备主键ID
        List<Long> list = handSendDto.getIds();
        //普通开阀
        if (dtoType.equals("0")){
            for (String room : roomNo) {
                //设备数据详情 (锁闭阀)
                ControlValve controlValve = ctrlValveMapper.selectControlValveByRoomNoLock(room);
                //单元阀
                ControlValve controlValve1 = ctrlValveMapper.selectControlValveByRoomNoUnit(room);
                if (controlValve != null) {


                    //集中器ID（设备ID）
                    String nodeId = controlValve.getNodeId();
                    //设备ID编码
                    String string = twoByte(nodeId);
                    //计量点ID
                    String meternum = controlValve.getMeternum();
                    int i = Integer.parseInt(meternum);
                    // 将十进制数转换为两位十六进制字符串
                    String hexString = String.format("%02x", i);
                    //校验和
                    // 输入的十六进制字符串
                    String hex1 = "18";
                    String hex2 = string.substring(0,2);
                    String hex3 = string.substring(2,4);
                    String hex4 = hexString;
                    String hex5 = "66";

                    // 将十六进制字符串转换为十进制整数
                    int num1 = Integer.parseInt(hex1, 16);
                    int num2 = Integer.parseInt(hex2, 16);
                    int num3 = Integer.parseInt(hex3, 16);
                    int num4 = Integer.parseInt(hex4, 16);
                    int num5 = Integer.parseInt(hex5, 16);

                    // 执行加法运算
                    int result = num1 + num2 + num3 + num4 + num5;
                    // 只提取结果的后两位
                    String hexResult = Integer.toHexString(result);
                    if (hexResult.length() > 2) {
                        hexResult = hexResult.substring(hexResult.length() - 2);
                    }
                    //普通开阀编码为
                    String codes=code+string+hexString+"66"+hexResult;
                    System.out.println(hexResult);
                    //使用redis发布到指定频道号
                    publish(codes);
                    //接受回执码 判断是否成功

                }else if (controlValve1!=null){
                    //集中器ID（设备ID）
                    String nodeId = controlValve1.getNodeId();
                    //设备ID编码
                    String string = twoByte(nodeId);
                    //计量点ID
                    String meternum = controlValve1.getMeternum();
                    int i = Integer.parseInt(meternum);
                    // 将十进制数转换为两位十六进制字符串
                    String hexString = String.format("%02x", i);
                    //校验和
                    // 输入的十六进制字符串
                    String hex1 = "18";
                    String hex2 = string.substring(0,2);
                    String hex3 = string.substring(2,4);
                    String hex4 = hexString;
                    String hex5 = "66";

                    // 将十六进制字符串转换为十进制整数
                    int num1 = Integer.parseInt(hex1, 16);
                    int num2 = Integer.parseInt(hex2, 16);
                    int num3 = Integer.parseInt(hex3, 16);
                    int num4 = Integer.parseInt(hex4, 16);
                    int num5 = Integer.parseInt(hex5, 16);

                    // 执行加法运算
                    int result = num1 + num2 + num3 + num4 + num5;
                    // 只提取结果的后两位
                    String hexResult = Integer.toHexString(result);
                    if (hexResult.length() > 2) {
                        hexResult = hexResult.substring(hexResult.length() - 2);
                    }
                    //普通开阀编码为
                    String codes=code+string+hexString+"66"+hexResult;
                    System.out.println(hexResult);
                    //使用redis发布到指定频道号
                    publish(codes);
                    //接受回执码 判断是否成功
                }
            }

            //普通关阀
        }else if (dtoType.equals("1")){
            for (String room : roomNo) {
                //设备数据详情
                ControlValve controlValve = ctrlValveMapper.selectControlValveByRoomNoLock(room);
                ControlValve controlValve1 = ctrlValveMapper.selectControlValveByRoomNoUnit(room);
                if (controlValve != null) {


                    //集中器ID（设备ID）
                    String nodeId = controlValve.getNodeId();
                    //设备ID编码
                    String string = twoByte(nodeId);
                    //计量点ID
                    String meternum = controlValve.getMeternum();
                    int i = Integer.parseInt(meternum);
                    // 将十进制数转换为两位十六进制字符串
                    String hexString = String.format("%02x", i);
                    //校验和
                    // 输入的十六进制字符串
                    String hex1 = "18";
                    String hex2 = string.substring(0,2);
                    String hex3 = string.substring(2,4);
                    String hex4 = hexString;
                    String hex5 = "77";

                    // 将十六进制字符串转换为十进制整数
                    int num1 = Integer.parseInt(hex1, 16);
                    int num2 = Integer.parseInt(hex2, 16);
                    int num3 = Integer.parseInt(hex3, 16);
                    int num4 = Integer.parseInt(hex4, 16);
                    int num5 = Integer.parseInt(hex5, 16);

                    // 执行加法运算
                    int result = num1 + num2 + num3 + num4 + num5;
                    // 只提取结果的后两位
                    String hexResult = Integer.toHexString(result);
                    if (hexResult.length() > 2) {
                        hexResult = hexResult.substring(hexResult.length() - 2);
                    }
                    //普通开阀编码为
                    String codes=code+string+hexString+"77"+hexResult;
                    System.out.println(hexResult);
                    //使用redis发布到指定频道号
                    publish(codes);
                }else if (controlValve1!=null){
                    //集中器ID（设备ID）
                    String nodeId = controlValve1.getNodeId();
                    //设备ID编码
                    String string = twoByte(nodeId);
                    //计量点ID
                    String meternum = controlValve1.getMeternum();
                    int i = Integer.parseInt(meternum);
                    // 将十进制数转换为两位十六进制字符串
                    String hexString = String.format("%02x", i);
                    //校验和
                    // 输入的十六进制字符串
                    String hex1 = "18";
                    String hex2 = string.substring(0,2);
                    String hex3 = string.substring(2,4);
                    String hex4 = hexString;
                    String hex5 = "77";

                    // 将十六进制字符串转换为十进制整数
                    int num1 = Integer.parseInt(hex1, 16);
                    int num2 = Integer.parseInt(hex2, 16);
                    int num3 = Integer.parseInt(hex3, 16);
                    int num4 = Integer.parseInt(hex4, 16);
                    int num5 = Integer.parseInt(hex5, 16);

                    // 执行加法运算
                    int result = num1 + num2 + num3 + num4 + num5;
                    // 只提取结果的后两位
                    String hexResult = Integer.toHexString(result);
                    if (hexResult.length() > 2) {
                        hexResult = hexResult.substring(hexResult.length() - 2);
                    }
                    //普通开阀编码为
                    String codes=code+string+hexString+"77"+hexResult;
                    System.out.println(hexResult);
                    //使用redis发布到指定频道号
                    publish(codes);
                }
            }

            //强制开阀
        }else if (dtoType.equals("2")){
            for (String room : roomNo) {
                //设备数据详情
                ControlValve controlValve = ctrlValveMapper.selectControlValveByRoomNoLock(room);
                ControlValve controlValve1 = ctrlValveMapper.selectControlValveByRoomNoUnit(room);
                if (controlValve != null) {


                    //集中器ID（设备ID）
                    String nodeId = controlValve.getNodeId();
                    //设备ID编码
                    String string = twoByte(nodeId);
                    //计量点ID
                    String meternum = controlValve.getMeternum();
                    int i = Integer.parseInt(meternum);
                    // 将十进制数转换为两位十六进制字符串
                    String hexString = String.format("%02x", i);
                    //校验和
                    // 输入的十六进制字符串
                    String hex1 = "18";
                    String hex2 = string.substring(0,2);
                    String hex3 = string.substring(2,4);
                    String hex4 = hexString;
                    String hex5 = "55";

                    // 将十六进制字符串转换为十进制整数
                    int num1 = Integer.parseInt(hex1, 16);
                    int num2 = Integer.parseInt(hex2, 16);
                    int num3 = Integer.parseInt(hex3, 16);
                    int num4 = Integer.parseInt(hex4, 16);
                    int num5 = Integer.parseInt(hex5, 16);

                    // 执行加法运算
                    int result = num1 + num2 + num3 + num4 + num5;
                    // 只提取结果的后两位
                    String hexResult = Integer.toHexString(result);
                    if (hexResult.length() > 2) {
                        hexResult = hexResult.substring(hexResult.length() - 2);
                    }
                    //普通开阀编码为
                    String codes=code+string+hexString+"55"+hexResult;
                    System.out.println(hexResult);
                    //使用redis发布到指定频道号
                    publish(codes);
                    Thread.sleep(1500);//暂停1.5秒
                    ControlRecords controlRecords=controlRecordsMapper.selectControlRecordsByEId(controlValve.getNodeId(),controlValve.getMeternum());
                    if (controlRecords != null){
                        if (controlRecords.getField1().equals("成功")){
                            results.add("房间"+controlRecords.getRoom()+"设备调控成功");
                            System.out.println("controlRecords = " + "设备进行了调控");
                        }else {
                            results.add("房间"+controlRecords.getRoom()+"设备调控失败！");
                            System.out.println("controlRecords = " + "设备调控失败");
                        }
                    }
                }else if (controlValve1!=null){
                    //集中器ID（设备ID）
                    String nodeId = controlValve1.getNodeId();
                    //设备ID编码
                    String string = twoByte(nodeId);
                    //计量点ID
                    String meternum = controlValve1.getMeternum();
                    int i = Integer.parseInt(meternum);
                    // 将十进制数转换为两位十六进制字符串
                    String hexString = String.format("%02x", i);
                    //校验和
                    // 输入的十六进制字符串
                    String hex1 = "18";
                    String hex2 = string.substring(0,2);
                    String hex3 = string.substring(2,4);
                    String hex4 = hexString;
                    String hex5 = "55";

                    // 将十六进制字符串转换为十进制整数
                    int num1 = Integer.parseInt(hex1, 16);
                    int num2 = Integer.parseInt(hex2, 16);
                    int num3 = Integer.parseInt(hex3, 16);
                    int num4 = Integer.parseInt(hex4, 16);
                    int num5 = Integer.parseInt(hex5, 16);

                    // 执行加法运算
                    int result = num1 + num2 + num3 + num4 + num5;
                    // 只提取结果的后两位
                    String hexResult = Integer.toHexString(result);
                    if (hexResult.length() > 2) {
                        hexResult = hexResult.substring(hexResult.length() - 2);
                    }
                    //普通开阀编码为
                    String codes=code+string+hexString+"55"+hexResult;
                    System.out.println(hexResult);
                    //使用redis发布到指定频道号
                    publish(codes);
                    Thread.sleep(1500);//暂停1.5秒
                    ControlRecords controlRecords=controlRecordsMapper.selectControlRecordsByEId(controlValve1.getNodeId(),controlValve1.getMeternum());
                    if (controlRecords != null){
                        if (controlRecords.getField1().equals("成功")){
                            results.add("房间"+controlRecords.getRoom()+"设备调控成功");
                            System.out.println("controlRecords = " + "设备进行了调控");
                        }else {
                            results.add("房间"+controlRecords.getRoom()+"设备调控失败！");
                            System.out.println("controlRecords = " + "设备调控失败");
                        }
                    }

                }
            }

            //强制关阀
        }else if (dtoType.equals("3")){
            for (String room : roomNo) {
                //设备数据详情
                ControlValve controlValve = ctrlValveMapper.selectControlValveByRoomNoLock(room);
                ControlValve controlValve1 = ctrlValveMapper.selectControlValveByRoomNoUnit(room);
                if (controlValve != null) {


                    //集中器ID（设备ID）
                    String nodeId = controlValve.getNodeId();
                    //设备ID编码
                    String string = twoByte(nodeId);
                    //计量点ID
                    String meternum = controlValve.getMeternum();
                    int i = Integer.parseInt(meternum);
                    // 将十进制数转换为两位十六进制字符串
                    String hexString = String.format("%02x", i);
                    //校验和
                    // 输入的十六进制字符串
                    String hex1 = "18";
                    String hex2 = string.substring(0,2);
                    String hex3 = string.substring(2,4);
                    String hex4 = hexString;
                    String hex5 = "99";

                    // 将十六进制字符串转换为十进制整数
                    int num1 = Integer.parseInt(hex1, 16);
                    int num2 = Integer.parseInt(hex2, 16);
                    int num3 = Integer.parseInt(hex3, 16);
                    int num4 = Integer.parseInt(hex4, 16);
                    int num5 = Integer.parseInt(hex5, 16);

                    // 执行加法运算
                    int result = num1 + num2 + num3 + num4 + num5;
                    // 只提取结果的后两位
                    String hexResult = Integer.toHexString(result);
                    if (hexResult.length() > 2) {
                        hexResult = hexResult.substring(hexResult.length() - 2);
                    }
                    System.out.println(hexResult);
                    //普通开阀编码为
                    String codes=code+string+hexString+"99"+hexResult;
                    System.out.println(codes);
                    //使用redis发布到指定频道号
                    publish(codes);
                    Thread.sleep(1500);//暂停1.5秒
                    ControlRecords controlRecords=controlRecordsMapper.selectControlRecordsByEId(controlValve.getNodeId(),controlValve.getMeternum());
                    if (controlRecords != null){
                        if (controlRecords.getField1().equals("成功")){
                            results.add("房间"+controlRecords.getRoom()+"设备调控成功");
                            System.out.println("controlRecords = " + "设备进行了调控");
                        }else {
                            results.add("房间"+controlRecords.getRoom()+"设备调控失败！");
                            System.out.println("controlRecords = " + "设备调控失败");
                        }
                    }
                    //deng
//                    String message = RedisMessageHandlers.message;
//                    System.out.println("message!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!! = " + message);

//                    // todo 引入等待机制
//                    try {
//                        System.err.println("*-*-*-*-正在等待回执码-*-*-*-*-");
//
//                        // Wait for the response with a timeout
//                        String resultCode = futureResponse.get(6, TimeUnit.SECONDS);

//                        //输出回执码
//                        System.err.println("Received Code*-*-*--*-*-*-*-*-*-*-*-*-**-*-: " + resultCode);
//                        // todo 接收到回执码后 进行逻辑处理
//                    } catch (InterruptedException | ExecutionException | TimeoutException e) {
//                        e.printStackTrace();
//                        throw new ServiceException("设备调控失败！.");
//                    }
                }else if (controlValve1!=null){
                    //集中器ID（设备ID）
                    String nodeId = controlValve1.getNodeId();
                    //设备ID编码
                    String string = twoByte(nodeId);
                    //计量点ID
                    String meternum = controlValve1.getMeternum();
                    int i = Integer.parseInt(meternum);
                    // 将十进制数转换为两位十六进制字符串
                    String hexString = String.format("%02x", i);
                    //校验和
                    // 输入的十六进制字符串
                    String hex1 = "18";
                    String hex2 = string.substring(0,2);
                    String hex3 = string.substring(2,4);
                    String hex4 = hexString;
                    String hex5 = "99";

                    // 将十六进制字符串转换为十进制整数
                    int num1 = Integer.parseInt(hex1, 16);
                    int num2 = Integer.parseInt(hex2, 16);
                    int num3 = Integer.parseInt(hex3, 16);
                    int num4 = Integer.parseInt(hex4, 16);
                    int num5 = Integer.parseInt(hex5, 16);

                    // 执行加法运算
                    int result = num1 + num2 + num3 + num4 + num5;
                    // 只提取结果的后两位
                    String hexResult = Integer.toHexString(result);
                    if (hexResult.length() > 2) {
                        hexResult = hexResult.substring(hexResult.length() - 2);
                    }
                    System.out.println(hexResult);
                    //普通开阀编码为
                    String codes=code+string+hexString+"99"+hexResult;
                    System.out.println(codes);
                    //使用redis发布到指定频道号
                    publish(codes);
                    Thread.sleep(1500);//暂停1.5秒
                    ControlRecords controlRecords=controlRecordsMapper.selectControlRecordsByEId(controlValve1.getNodeId(),controlValve1.getMeternum());
                    if (controlRecords != null){
                        if (controlRecords.getField1().equals("成功")){
                            results.add("房间"+controlRecords.getRoom()+"设备调控成功");
                            System.out.println("controlRecords = " + "设备进行了调控");
                        }else {
                            results.add("房间"+controlRecords.getRoom()+"设备调控失败！");
                            System.out.println("controlRecords = " + "设备调控失败");
                        }
                    }
                }
            }

            //阀门开度设置
        }else if (dtoType.equals("4")){
            String codes = "EB90EB90EB900C18";
            for (String room : roomNo) {
                //设备数据详情
                ControlValve controlValve = ctrlValveMapper.selectControlValveByRoomNoFlow(room);
                ControlValve controlValve1 = ctrlValveMapper.selectControlValveByRoomNoUnit(room);
                if (controlValve != null){

//                    EB90EB90EB900C18 8900 82 01 0073 00000000 97   137  130  2楼5单元502  开度73
//                    EB90EB90EB900C18 8900 82 01 0023 00000000 47   137  130  2楼5单元502  开度23
                    //集中器ID（设备ID）
                    String nodeId = controlValve.getNodeId();
                    //设备ID编码
                    String string = twoByte(nodeId);
                    //计量点ID
                    String meternum = controlValve.getMeternum();
                    int i = Integer.parseInt(meternum);
                    // 将十进制数转换为两位十六进制字符串
                    String hexString = String.format("%02x", i);
                    //todo 校验和（未确定怎么求取）

                    //   开50 "EB90EB90EB900C18A30001010050000000000D";
//            //设备1开度99
//            String kai99 = "EB90EB90EB900C18A300010100990000000056";
                    String hex1 = "18";
                    String hex2 = string.substring(0,2);
                    String hex3 = string.substring(2,4);
                    String hex4 = hexString;
                    String hex5 = "01";

                    // 将十六进制字符串转换为十进制整数
                    int num1 = Integer.parseInt(hex1, 16);
                    int num2 = Integer.parseInt(hex2, 16);
                    int num3 = Integer.parseInt(hex3, 16);
                    int num4 = Integer.parseInt(hex4, 16);
                    int num5 = Integer.parseInt(hex5, 16);
                    int num6 = Integer.parseInt(handSendDto.getValue(), 16);
                    // 执行加法运算
                    int result = num1 + num2 + num3 + num4 + num5+num6;
                    // 只提取结果的后两位
                    String hexResult = Integer.toHexString(result);
                    if (hexResult.length() > 2) {
                        hexResult = hexResult.substring(hexResult.length() - 2);
                    }
                    System.out.println(hexResult);
                    String string1 = convertToBCD(handSendDto.getValue());
                    String string2 = "00000000";
                    String code1=codes+string+hexString+hex5+string1+string2+hexResult;
                    System.out.println("阀门开度编码----------------"+code1);
                    publish(code1);
                    Thread.sleep(1500);//暂停1.5秒
                    ControlRecords controlRecords=controlRecordsMapper.selectControlRecordsByEId(controlValve.getNodeId(),controlValve.getMeternum());
                        if (controlRecords != null){
                            if (controlRecords.getField1().equals("成功")){
                                results.add("房间"+controlRecords.getRoom()+"设备调控成功");
                                System.out.println("controlRecords = " + "设备进行了调控");
                            }else {
                                results.add("房间"+controlRecords.getRoom()+"设备调控失败！");
                                System.out.println("controlRecords = " + "设备调控失败");
                            }
                        }

//                    // todo 引入等待机制
//                    try {
//                        System.err.println("*-*-*-*-正在等待回执码-*-*-*-*-");
//
//                        // Wait for the response with a timeout
//                        String resultCode = futureResponse.get(5, TimeUnit.SECONDS);
//                        //输出回执码
//                        System.err.println("Received Code*-*-*--*-*-*-*-*-*-*-*-*-**-*-: " + resultCode);
//                        // todo 接收到回执码后 进行逻辑处理
//                        ControlRecords controlRecords=controlRecordsMapper.selectControlRecordsByEId(controlValve.getNodeId(),controlValve.getMeternum());
//                        if (controlRecords != null){
//                            if (controlRecords.getField1().equals("成功")){
//                                System.out.println("controlRecords = " + "设备进行了调控");
//                            }
//                        }
//                    } catch (InterruptedException | ExecutionException | TimeoutException e) {
//                        e.printStackTrace();
//                        throw new ServiceException("Failed to receive response in time.");
//                    }
                }else if (controlValve1!=null){
                    //集中器ID（设备ID）
                    String nodeId = controlValve1.getNodeId();
                    //设备ID编码
                    String string = twoByte(nodeId);
                    //计量点ID
                    String meternum = controlValve1.getMeternum();
                    int i = Integer.parseInt(meternum);
                    // 将十进制数转换为两位十六进制字符串
                    String hexString = String.format("%02x", i);
                    //todo 校验和（未确定怎么求取）

                    //   开50 "EB90EB90EB900C18A30001010050000000000D";
//            //设备1开度99
//            String kai99 = "EB90EB90EB900C18A300010100990000000056";
                    String hex1 = "18";
                    String hex2 = string.substring(0,2);
                    String hex3 = string.substring(2,4);
                    String hex4 = hexString;
                    String hex5 = "01";

                    // 将十六进制字符串转换为十进制整数
                    int num1 = Integer.parseInt(hex1, 16);
                    int num2 = Integer.parseInt(hex2, 16);
                    int num3 = Integer.parseInt(hex3, 16);
                    int num4 = Integer.parseInt(hex4, 16);
                    int num5 = Integer.parseInt(hex5, 16);
                    int num6 = Integer.parseInt(handSendDto.getValue(), 16);
                    // 执行加法运算
                    int result = num1 + num2 + num3 + num4 + num5+num6;
                    // 只提取结果的后两位
                    String hexResult = Integer.toHexString(result);
                    if (hexResult.length() > 2) {
                        hexResult = hexResult.substring(hexResult.length() - 2);
                    }
                    System.out.println(hexResult);
                    String string1 = convertToBCD(handSendDto.getValue());
                    String string2 = "00000000";
                    String code1=codes+string+hexString+hex5+string1+string2+hexResult;
                    System.out.println("阀门开度编码----------------"+code1);
                    publish(code1);
                    Thread.sleep(1500);//暂停1.5秒
                    ControlRecords controlRecords=controlRecordsMapper.selectControlRecordsByEId(controlValve1.getNodeId(),controlValve1.getMeternum());
                    if (controlRecords != null){
                        if (controlRecords.getField1().equals("成功")){
                            results.add("房间"+controlRecords.getRoom()+"设备调控成功");
                            System.out.println("controlRecords = " + "设备进行了调控");
                        }else {
                            results.add("房间"+controlRecords.getRoom()+"设备调控失败！");
                            System.out.println("controlRecords = " + "设备调控失败");
                        }
                    }



                    // todo 引入等待机制

                }
            }

            //阀门开度比例调大
        }else if (dtoType.equals("5")){
            String codes = "EB90EB90EB900C18";
            for (String room : roomNo) {
                //设备数据详情
                ControlValve controlValve = ctrlValveMapper.selectControlValveByRoomNoFlow(room);
                ControlValve controlValve1 = ctrlValveMapper.selectControlValveByRoomNoUnit(room);
                if (controlValve != null){


                    //集中器ID（设备ID）
                    String nodeId = controlValve.getNodeId();
                    //设备ID编码
                    String string = twoByte(nodeId);
                    //计量点ID
                    String meternum = controlValve.getMeternum();
                    int m = Integer.parseInt(meternum);
                    // 将十进制数转换为两位十六进制字符串
                    String hexString = String.format("%02x", m);
                    //原设备开合度
                    String valveangle = controlValve.getValveangle();
                    //调大值
                    String big = handSendDto.getBig();
                    //todo 校验和（未确定怎么求取）

                    //   开50 "EB90EB90EB900C18A30001010050000000000D";
//            //设备1开度99
//            String kai99 = "EB90EB90EB900C18A300010100990000000056";
                    String hex1 = "18";
                    String hex2 = string.substring(0,2);
                    String hex3 = string.substring(2,4);
                    String hex4 = hexString;
                    String hex5 = "01";

                    // 将十六进制字符串转换为十进制整数
                    int num1 = Integer.parseInt(hex1, 16);
                    int num2 = Integer.parseInt(hex2, 16);
                    int num3 = Integer.parseInt(hex3, 16);
                    int num4 = Integer.parseInt(hex4, 16);
                    int num5 = Integer.parseInt(hex5, 16);
                    double i1 = Double.parseDouble(handSendDto.getBig())/100;
                    double i = Double.parseDouble(valveangle)*(1+i1);
                    int values= (int) i;
                    //调大后的开合度
                    String value = String.valueOf(values);
                    System.out.println("开合度为-----"+value);
                    int num6 = Integer.parseInt(value, 16);
                    System.out.println("开合度编码为+++++++"+num6);
                    // 执行加法运算
                    int result = num1 + num2 + num3 + num4 + num5+num6;
                    // 只提取结果的后两位
                    String hexResult = Integer.toHexString(result);
                    if (hexResult.length() > 2) {
                        hexResult = hexResult.substring(hexResult.length() - 2);
                    }
                    System.out.println(hexResult);
                    String string1 = convertToBCD(value);
                    String string2 = "00000000";
                    String code1=codes+string+hexString+hex5+string1+string2+hexResult;
                    System.out.println("阀门开度编码----------------"+code1);
                    publish(code1);
                    Thread.sleep(1500);//暂停1.5秒
                    ControlRecords controlRecords=controlRecordsMapper.selectControlRecordsByEId(controlValve.getNodeId(),controlValve.getMeternum());
                    if (controlRecords != null){
                        if (controlRecords.getField1().equals("成功")){
                            results.add("房间"+controlRecords.getRoom()+"设备调控成功");
                            System.out.println("controlRecords = " + "设备进行了调控");
                        }else {
                            results.add("房间"+controlRecords.getRoom()+"设备调控失败！");
                            System.out.println("controlRecords = " + "设备调控失败");
                        }
                    }
                }else if (controlValve1!=null){
                    //集中器ID（设备ID）
                    String nodeId = controlValve1.getNodeId();
                    //设备ID编码
                    String string = twoByte(nodeId);
                    //计量点ID
                    String meternum = controlValve1.getMeternum();
                    int m = Integer.parseInt(meternum);
                    // 将十进制数转换为两位十六进制字符串
                    String hexString = String.format("%02x", m);
                    //todo 校验和（未确定怎么求取）

                    //   开50 "EB90EB90EB900C18A30001010050000000000D";
//            //设备1开度99
//            String kai99 = "EB90EB90EB900C18A300010100990000000056";
                    String hex1 = "18";
                    String hex2 = string.substring(0,2);
                    String hex3 = string.substring(2,4);
                    String hex4 = hexString;
                    String hex5 = "01";

                    // 将十六进制字符串转换为十进制整数
                    int num1 = Integer.parseInt(hex1, 16);
                    int num2 = Integer.parseInt(hex2, 16);
                    int num3 = Integer.parseInt(hex3, 16);
                    int num4 = Integer.parseInt(hex4, 16);
                    int num5 = Integer.parseInt(hex5, 16);
                    double i1 = Double.parseDouble(handSendDto.getBig())/100;
                    double i = Double.parseDouble(controlValve1.getValveangle())*(1+i1);
                    int values= (int) i;
                    //调大后的开合度
                    String value = String.valueOf(values);
                    System.out.println("开合度为-----"+value);
                    int num6 = Integer.parseInt(value, 16);
                    System.out.println("开合度编码为+++++++"+num6);
                    // 执行加法运算
                    int result = num1 + num2 + num3 + num4 + num5+num6;
                    // 只提取结果的后两位
                    String hexResult = Integer.toHexString(result);
                    if (hexResult.length() > 2) {
                        hexResult = hexResult.substring(hexResult.length() - 2);
                    }
                    System.out.println(hexResult);
                    String string1 = convertToBCD(value);
                    String string2 = "00000000";
                    String code1=codes+string+hexString+hex5+string1+string2+hexResult;
                    System.out.println("阀门开度编码----------------"+code1);
                    publish(code1);
                    Thread.sleep(1500);//暂停1.5秒
                    ControlRecords controlRecords=controlRecordsMapper.selectControlRecordsByEId(controlValve1.getNodeId(),controlValve1.getMeternum());
                    if (controlRecords != null){
                        if (controlRecords.getField1().equals("成功")){
                            results.add("房间"+controlRecords.getRoom()+"设备调控成功");
                            System.out.println("controlRecords = " + "设备进行了调控");
                        }else {
                            results.add("房间"+controlRecords.getRoom()+"设备调控失败！");
                            System.out.println("controlRecords = " + "设备调控失败");
                        }
                    }



                }
            }


            //阀门开度比例调小
        }else if (dtoType.equals("6")){

            String codes = "EB90EB90EB900C18";
            for (String room : roomNo) {
                //设备数据详情
                ControlValve controlValve = ctrlValveMapper.selectControlValveByRoomNoFlow(room);
                ControlValve controlValve1 = ctrlValveMapper.selectControlValveByRoomNoUnit(room);
                if (controlValve != null){


                    //集中器ID（设备ID）
                    String nodeId = controlValve.getNodeId();
                    //设备ID编码
                    String string = twoByte(nodeId);
                    //计量点ID
                    String meternum = controlValve.getMeternum();
                    int m = Integer.parseInt(meternum);
                    // 将十进制数转换为两位十六进制字符串
                    String hexString = String.format("%02x", m);
                    //原设备开合度
                    String valveangle = controlValve.getValveangle();
                    //todo 校验和（未确定怎么求取）

                    //   开50 "EB90EB90EB900C18A30001010050000000000D";
//            //设备1开度99
//            String kai99 = "EB90EB90EB900C18A300010100990000000056";
                    String hex1 = "18";
                    String hex2 = string.substring(0,2);
                    String hex3 = string.substring(2,4);
                    String hex4 = hexString;
                    String hex5 = "01";

                    // 将十六进制字符串转换为十进制整数
                    int num1 = Integer.parseInt(hex1, 16);
                    int num2 = Integer.parseInt(hex2, 16);
                    int num3 = Integer.parseInt(hex3, 16);
                    int num4 = Integer.parseInt(hex4, 16);
                    int num5 = Integer.parseInt(hex5, 16);
                    double i1 = Double.parseDouble(handSendDto.getBig())/100;
                    double i = Double.parseDouble(valveangle)*(1-i1);
                    int values= (int) i;
                    //调小后的开合度
                    String value = String.valueOf(values);
                    System.out.println("开合度为-----"+value);
                    int num6 = Integer.parseInt(value, 16);
                    System.out.println("开合度编码为+++++++"+num6);
                    // 执行加法运算
                    int result = num1 + num2 + num3 + num4 + num5+num6;
                    // 只提取结果的后两位
                    String hexResult = Integer.toHexString(result);
                    if (hexResult.length() > 2) {
                        hexResult = hexResult.substring(hexResult.length() - 2);
                    }
                    System.out.println(hexResult);
                    String string1 = convertToBCD(value);
                    String string2 = "00000000";
                    String code1=codes+string+hexString+hex5+string1+string2+hexResult;
                    System.out.println("阀门开度编码----------------"+code1);
                    publish(code1);
                    Thread.sleep(1500);//暂停1.5秒
                    ControlRecords controlRecords=controlRecordsMapper.selectControlRecordsByEId(controlValve.getNodeId(),controlValve.getMeternum());
                    if (controlRecords != null){
                        if (controlRecords.getField1().equals("成功")){
                            results.add("房间"+controlRecords.getRoom()+"设备调控成功");
                            System.out.println("controlRecords = " + "设备进行了调控");
                        }else {
                            results.add("房间"+controlRecords.getRoom()+"设备调控失败！");
                            System.out.println("controlRecords = " + "设备调控失败");
                        }
                    }
                }else if (controlValve1!=null){
                    //集中器ID（设备ID）
                    String nodeId = controlValve1.getNodeId();
                    //设备ID编码
                    String string = twoByte(nodeId);
                    //计量点ID
                    String meternum = controlValve1.getMeternum();
                    int m = Integer.parseInt(meternum);
                    // 将十进制数转换为两位十六进制字符串
                    String hexString = String.format("%02x", m);
                    //todo 校验和（未确定怎么求取）


                    //   开50 "EB90EB90EB900C18A30001010050000000000D";
//            //设备1开度99
//            String kai99 = "EB90EB90EB900C18A300010100990000000056";
                    String hex1 = "18";
                    String hex2 = string.substring(0,2);
                    String hex3 = string.substring(2,4);
                    String hex4 = hexString;
                    String hex5 = "01";

                    // 将十六进制字符串转换为十进制整数
                    int num1 = Integer.parseInt(hex1, 16);
                    int num2 = Integer.parseInt(hex2, 16);
                    int num3 = Integer.parseInt(hex3, 16);
                    int num4 = Integer.parseInt(hex4, 16);
                    int num5 = Integer.parseInt(hex5, 16);
                    double i1 = Double.parseDouble(handSendDto.getBig())/100;
                    double i = Double.parseDouble(controlValve1.getValveangle())*(1-i1);
                    int values= (int) i;
                    //调小后的开合度
                    String value = String.valueOf(values);
                    System.out.println("开合度为-----"+value);
                    int num6 = Integer.parseInt(value, 16);
                    System.out.println("开合度编码为+++++++"+num6);
                    // 执行加法运算
                    int result = num1 + num2 + num3 + num4 + num5+num6;
                    // 只提取结果的后两位
                    String hexResult = Integer.toHexString(result);
                    if (hexResult.length() > 2) {
                        hexResult = hexResult.substring(hexResult.length() - 2);
                    }
                    System.out.println(hexResult);
                    String string1 = convertToBCD(value);
                    String string2 = "00000000";
                    String code1=codes+string+hexString+hex5+string1+string2+hexResult;
                    System.out.println("阀门开度编码----------------"+code1);
                    publish(code1);
                    Thread.sleep(1500);//暂停1.5秒
                    ControlRecords controlRecords=controlRecordsMapper.selectControlRecordsByEId(controlValve1.getNodeId(),controlValve1.getMeternum());
                    if (controlRecords != null){
                        if (controlRecords.getField1().equals("成功")){
                            results.add("房间"+controlRecords.getRoom()+"设备调控成功");
                            System.out.println("controlRecords = " + "设备进行了调控");
                        }else {
                            results.add("房间"+controlRecords.getRoom()+"设备调控失败！");
                            System.out.println("controlRecords = " + "设备调控失败");
                        }
                    }



                }
            }

        }
return results;
    }
    /**
     * 温控阀发送指令(自动调控)
     * @param autoSendDto
     * @return
     */
    @Override
    public int AutoSendConxtrolValve(AutoSendDto autoSendDto) {
        //todo 将传参数据存入至温控阀操控记录表中
        //接受传过来的参数 将操作的设备指令入库
        String type = autoSendDto.getType();
        List<String> roomNos = autoSendDto.getRoomNo();
        if (type.equals("7")){
            //回水温度自动调控
            for (String roomNo : roomNos) {

                ControlRecords controlRecords = new ControlRecords();
                RoomInfo roomInfo = roomInfoMapper.selectRoomInfoByRoomNo(roomNo);
                ControlValve controlValve = ctrlValveMapper.selectControlValveByRoomNo(roomNo);
                if (controlValve != null) {
                    //设备ID（计量点ID）
                    controlRecords.setNodeId(controlValve.getMeternum());
                    //所属厂家
                    controlRecords.setManufactor(controlValve.getManufactor());
                }else {
                    throw new ServiceException("未检测到该房间或单元下的阀门，无法进行调控！");

//                    //设备ID（计量点ID）
//                    controlRecords.setNodeId("01");
//                    //所属厂家
//                    controlRecords.setManufactor("0");
                }
                //操作房间
                controlRecords.setRoom(roomInfo.getCommunityName()+"-"+roomInfo.getBuildingName()+"-"+roomInfo.getUnitName()+"-"+roomInfo.getHouseNumber());
                //操作内容
                controlRecords.setContent("将设备进行回水温度自动调控操作");
                //回水温度自动调控设置值
                controlRecords.setValue(autoSendDto.getValue());
                //操作码
                controlRecords.setCode("");
                //操作结果
//                controlRecords.setField1("成功");
                //操作时间
                controlRecords.setCreateTime(new Date());
                //操作人
                controlRecords.setCreateBy(SecurityUtils.getUsername());
                //调控类型
                controlRecords.setField5("自动调控");
                //操作类型
                controlRecords.setType(type);
                //操作用户ID
                controlRecords.setDeptId(SecurityUtils.getUserId());

                controlRecordsMapper.insertControlRecords(controlRecords);
            }

        }else if (type.equals("8")){
            //温差调控
            for (String roomNo : roomNos) {

                ControlRecords controlRecords = new ControlRecords();
                RoomInfo roomInfo = roomInfoMapper.selectRoomInfoByRoomNo(roomNo);
                ControlValve controlValve = ctrlValveMapper.selectControlValveByRoomNo(roomNo);
                if (controlValve != null) {
                    //设备ID（计量点ID）
                    controlRecords.setNodeId(controlValve.getMeternum());
                    //所属厂家
                    controlRecords.setManufactor(controlValve.getManufactor());
                }else {
                    throw new ServiceException("未检测到该房间或单元下的阀门，无法进行调控！");

//                    //设备ID（计量点ID）
//                    controlRecords.setNodeId("01");
//                    //所属厂家
//                    controlRecords.setManufactor("0");
                }
                //操作房间
                controlRecords.setRoom(roomInfo.getCommunityName()+"-"+roomInfo.getBuildingName()+"-"+roomInfo.getUnitName()+"-"+roomInfo.getHouseNumber());
                //操作内容
                controlRecords.setContent("将设备进行自动温差调控操作");
                //温差自动调控设置值
                controlRecords.setValue(autoSendDto.getValue());
                //操作码
                controlRecords.setCode("");
                //操作结果
//                controlRecords.setField1("成功");
                //操作时间
                controlRecords.setCreateTime(new Date());
                //操作人
                controlRecords.setCreateBy(SecurityUtils.getUsername());
                //调控类型
                controlRecords.setField5("自动调控");
                //操作类型
                controlRecords.setType(type);
                //操作用户ID
                controlRecords.setDeptId(SecurityUtils.getUserId());

                controlRecordsMapper.insertControlRecords(controlRecords);
            }

        }
        return 1;
    }

    /**
     * 查询户用流量阀采集数据列表
     */
    @Override
    public List<ControlValve> selectControlValveListFiow(ControlValve controlValve) {
        List<ControlValve> controlValves = ctrlValveMapper.selectControlValveListFiow(controlValve);
        for (ControlValve controlValf : controlValves) {
            //进回水温度（从热表中获取）
            String roomNo = controlValf.getRoomNo();
            HeatInfo heatInfo= heatInfoMapper.selectHeatInfoByRonmNo(roomNo);
            if (heatInfo != null){
                BigDecimal inletTemp = heatInfo.getInletTemp();
                BigDecimal outTemp = heatInfo.getOutTemp();
                controlValf.setIntemp(String.valueOf(inletTemp));
                controlValf.setOuttemp(String.valueOf(outTemp));
                String string = String.valueOf(inletTemp);
                String string1 = String.valueOf(outTemp);
                //温差 Field2
                // 计算温差
                double temperatureDifference = calculateTemperatureDifference(string,string1);
                String format = String.format("%.2f", temperatureDifference);
                controlValf.setField2(format);
            }else if (controlValf.getIntemp()!=null&&controlValf.getOuttemp()!=null){
                // 计算温差
                double temperatureDifference = calculateTemperatureDifference(controlValf.getIntemp(),controlValf.getOuttemp());
                String format = String.format("%.2f", temperatureDifference);
                controlValf.setField2(format);
            }

            //室温
            EquipmentDocking equipmentDocking = equipmentDockingMapper.selectEquipmentCountDockingByRoom(roomNo);
            if (equipmentDocking != null) {
                controlValf.setIndoortemp(String.valueOf(equipmentDocking.getTemp()));
            }

            //阀门状态
            String valveangle = controlValf.getValveangle();
            if (valveangle.equals("0")|| valveangle.isEmpty()){
                //关闭
                controlValf.setNc("0");
            }else{
                //开启
                controlValf.setNc("1");
            }



        }
        return controlValves;
    }

    /**
     * 查询户用锁闭阀采集数据列表
     */
    @Override
    public List<ControlValve> selectControlValveListLock(ControlValve controlValve) {
        List<ControlValve> controlValves = ctrlValveMapper.selectControlValveListLock(controlValve);
        for (ControlValve controlValf : controlValves) {
            //将进水温度的取值范围给查询出来，若是输入单个值的话
            //进回水温度（从热表中获取）
            String roomNo = controlValf.getRoomNo();
            HeatInfo heatInfo= heatInfoMapper.selectHeatInfoByRonmNo(roomNo);
            if (heatInfo!=null){
                BigDecimal inletTemp = heatInfo.getInletTemp();
                BigDecimal outTemp = heatInfo.getOutTemp();
                String string = String.valueOf(inletTemp);
                String string1 = String.valueOf(outTemp);
                controlValf.setIntemp(String.valueOf(inletTemp));
                controlValf.setOuttemp(String.valueOf(outTemp));
                //温差 Field2
                // 计算温差
                double temperatureDifference = calculateTemperatureDifference(string,string1);
                String format = String.format("%.2f", temperatureDifference);
                controlValf.setField2(format);
            }
            //室温
            EquipmentDocking equipmentDocking = equipmentDockingMapper.selectEquipmentCountDockingByRoom(roomNo);
            if (equipmentDocking != null) {
                controlValf.setIndoortemp(String.valueOf(equipmentDocking.getTemp()));
            }
            //阀门状态
            String valveangle = controlValf.getValveangle();
            if (valveangle.equals("0")|| valveangle.isEmpty()){
                //关闭
                controlValf.setNc("0");
            }else{
                //开启
                controlValf.setNc("1");
            }


        }
        return controlValves;
    }

    /**
     * 计算温差
     * @param intemp 进水温度，字符串格式
     * @param outtemp 回水温度，字符串格式
     * @return 温差，浮点数
     */
    public static double calculateTemperatureDifference(String intemp, String outtemp) {
        // 将字符串转换为浮点数
        double inTemperature = parseTemperature(intemp);
        double outTemperature = parseTemperature(outtemp);

        // 计算温差
        return inTemperature - outTemperature;
    }

    /**
     * 将温度字符串解析为浮点数
     * @param temperature 温度字符串
     * @return 温度，浮点数
     */
    private static double parseTemperature(String temperature) {
        try {
            return Double.parseDouble(temperature);
        } catch (NumberFormatException e) {
            // 如果解析失败，返回0.0作为默认值
            System.err.println("无法解析温度: " + temperature + ", 使用默认值0.0");
            return 0.0;
        }
    }

    /**
     * 查询单元阀采集数据列表
     */
    @Override
    public List<ControlValve> selectControlValveListUnit(ControlValve controlValve) {
        List<ControlValve> controlValves = ctrlValveMapper.selectControlValveListUnit(controlValve);
        for (ControlValve controlValf : controlValves) {
            //温差 Field2
            // 计算温差
            double temperatureDifference = calculateTemperatureDifference(controlValf.getIntemp(),controlValf.getOuttemp());
            String format = String.format("%.2f", temperatureDifference);
            controlValf.setField2(format);
            //阀门状态
            String valveangle = controlValf.getValveangle();
            if (valveangle.equals("0")|| valveangle.isEmpty()){
                //关闭
                controlValf.setNc("0");
            }else{
                //开启
                controlValf.setNc("1");
            }

        }
        return controlValves;
    }

    /**
     *
     * @param roomNo
     * @param state
     * @return
     */
    @Override
    public int sendConxtrolValveLock(String roomNo, String state) {
        return 0;
    }

    /**
     * 拉取最新阀门数据 判断当前房间的户型并更新（保百小区）
     */
    @Override
    public void updateHome() {
        ControlValve controlValve=new ControlValve();
        //获取当前最新房间的锁闭阀实时信息
        List<ControlValve> controlValves = this.selectControlValveListLock(controlValve);
        //根该房间的上、下房间的阀门状态来判断该该房间的最新户型状态
        for (ControlValve controlValf : controlValves) {
            String roomNumber = controlValf.getRoomName(); // 当前房间号
            String[] parts = roomNumber.split("-"); // 分割字符串
            int building = Integer.parseInt(parts[0]); // 楼栋
            int unit = Integer.parseInt(parts[1]); // 单元
            int room = Integer.parseInt(parts[2]); // 房间号
            String upperRoom = building + "-" + unit + "-" + (room + 100); // 上层房间号
            String lowerRoom = building + "-" + unit + "-" + (room - 100); // 下层房间号
            //当前房间的房间编号
            String roomNo = controlValf.getRoomNo();
            //查询上层房间号
            ControlValve roomName=ctrlValveMapper.selectControlValveByRoomName(upperRoom);
            if (roomName == null) {
                throw new ServiceException("房间格式错误!");
            }
            //查询下层房间号
            ControlValve roomName1=ctrlValveMapper.selectControlValveByRoomName(lowerRoom);
            if (roomName1 == null) {
                throw new ServiceException("房间格式错误!");
            }
            if (String.valueOf(room).charAt(0) == '1'){//这间房间是底层
                //获取上层房间的阀门状态哦 开启|关闭
                String state = roomName.getState();
                if (state.equals("0")){//为下停户
                    //直接更新房间表中的数据
                    roomInfoMapper.updateRoomInfoByRoomNo(roomNo);
                }else if (state.equals("1")){//为孤岛户
                    //直接更新房间表中的数据
                    roomInfoMapper.updateRoomInfoByRoomNoZero(roomNo);
                }
            }
            if (String.valueOf(room).charAt(0) == '6'){//这间房间是顶层
                //获取上层房间的阀门状态哦 开启|关闭
                String state = roomName1.getState();
                if (state.equals("0")){//为上停户
                    //直接更新房间表中的数据
                    roomInfoMapper.updateRoomInfoByRoomNoOne(roomNo);
                }else if (state.equals("1")){//为孤岛户
                    //直接更新房间表中的数据
                    roomInfoMapper.updateRoomInfoByRoomNoZero(roomNo);
                }
            }
            //其余中间楼层
            //上层房间阀门状态
            String state = roomName.getState();
            //下层房间阀门状态
            String state1 = roomName.getState();
            //根据阀门状态判断户型
            if (state.equals("0")&&state1.equals("0")){//中间户
                roomInfoMapper.updateRoomInfoByRoomNoThree(roomNo);
            }else if (state.equals("0")&&state1.equals("1")){//下停户
                roomInfoMapper.updateRoomInfoByRoomNo(roomNo);
            }else if (state.equals("1")&&state1.equals("0")){//上停户
                roomInfoMapper.updateRoomInfoByRoomNoOne(roomNo);
            }else if (state.equals("1")&&state1.equals("1")){//孤岛户
                roomInfoMapper.updateRoomInfoByRoomNoZero(roomNo);
            }

        }
    }


    /**
     * 接收温控阀数据
     */
    @Override
    public String collectionControlValve() {
        //todo 从redis中根据key拿到数据，进行解析并保存至数据库

        return "EB90EB90EB900618";
    }

    /**
     * 将字符串转化成2字节的16进制 低字节在前
     * @param decimalString
     * @return
     */
    public String twoByte(String decimalString){
        int decimalValue = Integer.parseInt(decimalString);

        //创建一个字节数组来存储2字节表示
        byte[] byteArray = new byte[2];

        //用低字节填充字节数组
        byteArray[0] = (byte) (decimalValue & 0xFF);       // Low byte
        byteArray[1] = (byte) ((decimalValue >> 8) & 0xFF); // High byte

        ////将字节数组转换为十六进制字符串表示形式
        StringBuilder hexString = new StringBuilder();
        for (byte b : byteArray) {
            hexString.append(String.format("%02X", b));
        }
        return hexString.toString();
    }

    private static String convertToBCD(String decimalString) {
        // Ensure the string has exactly 4 digits for BCD representation
        if (decimalString.length() > 4) {
            throw new IllegalArgumentException("Input string must have at most 4 digits");
        }

        // Pad the string to 4 digits if it's shorter
        decimalString = String.format("%04d", Integer.parseInt(decimalString));

        StringBuilder bcdStringBuilder = new StringBuilder();

        // Convert each pair of characters into a BCD byte
        for (int i = 0; i < decimalString.length(); i += 2) {
            int firstDigit = Character.digit(decimalString.charAt(i), 10);
            int secondDigit = Character.digit(decimalString.charAt(i + 1), 10);
            // Combine two digits into a BCD byte
            int bcdValue = (firstDigit << 4) | secondDigit;
            bcdStringBuilder.append(String.format("%02X", bcdValue));
        }

        return bcdStringBuilder.toString();
    }








    private final ExecutorService executorService = Executors.newCachedThreadPool();

    // 发送控制阀指令的方法
    public List<String > sendControlValve(HandSendDto handSendDto) throws InterruptedException {
        String username = SecurityUtils.getUsername();
        List<String> codes;
//        List<String> roomNos = handSendDto.getRoomNo();
//        roomNos.forEach(room -> {

                    // 记录初始操作状态  插入
                    logControlOperation(handSendDto,username);
                    // 编码设备指令  发布到Redis频道
                    //编码 往redis发送数据
                    codes = code(handSendDto);
                    //等待
//        CompletableFuture.runAsync(() -> {
//            try {

//                } catch (Exception e) {
//                    e.printStackTrace();
//                    // 记录失败状态
////                    logControlOperation(handSendDto,username);
//                    throw new ServiceException("系统异常，请稍后重试！");
//                }
//
//            }, executorService);
//        });

        return codes;
    }



    // 将控制操作记录到数据库的方法
    private void logControlOperation(HandSendDto handSendDto,String username) {
        //接受传过来的参数 将操作的设备指令入库
        List<String> roomNos = handSendDto.getRoomNo();
        String type = handSendDto.getType();
        //开关阀操作
        if (type.equals("0") || type.equals("1") || type.equals("2") || type.equals("3")) {
            for (String roomNo : roomNos) {

                ControlRecords controlRecords = new ControlRecords();
                RoomInfo roomInfo = roomInfoMapper.selectRoomInfoByRoomNo(roomNo);
                //锁闭阀
                ControlValve controlValve = ctrlValveMapper.selectControlValveByRoomNoLock(roomNo);
                //流量阀
                ControlValve controlValve2 = ctrlValveMapper.selectControlValveByRoomNoFlow(roomNo);
                if (controlValve != null) {
                    //集中器ID
                    controlRecords.setField4(controlValve.getEid());
                    //设备ID（计量点ID）
                    controlRecords.setNodeId(controlValve.getMeternum());
                    //所属厂家
                    controlRecords.setManufactor(controlValve.getManufactor());
                    //操作房间
                    controlRecords.setRoom(roomInfo.getCommunityName() + "-" + roomInfo.getBuildingName() + "-" + roomInfo.getUnitName() + "-" + roomInfo.getHouseNumber());
                    //流量阀
                } else if (controlValve2 != null) {
                    //集中器ID
                    controlRecords.setField4(controlValve2.getEid());
                    //设备ID（计量点ID）
                    controlRecords.setNodeId(controlValve2.getMeternum());
                    //所属厂家
                    controlRecords.setManufactor(controlValve2.getManufactor());
                    //操作房间
                    controlRecords.setRoom(roomInfo.getCommunityName() + "-" + roomInfo.getBuildingName() + "-" + roomInfo.getUnitName() + "-" + roomInfo.getHouseNumber());
                } else {

                    ControlValve controlValve1 = ctrlValveMapper.selectControlValveByRoomNoUnit(roomNo);
                    if (controlValve1 != null) {
                        //集中器ID
                        controlRecords.setField4(controlValve1.getEid());
                        //设备ID（计量点ID）
                        controlRecords.setNodeId(controlValve1.getMeternum());
                        //所属厂家
                        controlRecords.setManufactor("0");
                    } else {
                        throw new ServiceException("未检测到该房间或单元下的阀门，无法进行调控！");
                    }
                    //操作房间
                    controlRecords.setRoom(controlValve1.getVillageName() + "-" + controlValve1.getBuildingName() + "-" + controlValve1.getUnitName() + "单元");
                }
                //操作类型
                controlRecords.setType(type);

                //操作内容
                controlRecords.setContent("将设备进行开关阀操作");
                //操作码
                controlRecords.setCode("");
                //操作结果
//                controlRecords.setField1("成功");
                //操作时间
                controlRecords.setCreateTime(new Date());
                //操作人
                controlRecords.setCreateBy(username);
                //调控类型
                controlRecords.setField5("0");
                //操作用户ID
                controlRecords.setDeptId(SecurityUtils.getUserId());
                controlRecordsMapper.insertControlRecords(controlRecords);
            }
            //阀门开度设置
        } else if (type.equals("4")) {
            for (String roomNo : roomNos) {

                ControlRecords controlRecords = new ControlRecords();
                RoomInfo roomInfo = roomInfoMapper.selectRoomInfoByRoomNo(roomNo);
                //流量阀
                ControlValve controlValve = ctrlValveMapper.selectControlValveByRoomNoFlow(roomNo);
                //锁闭阀
                ControlValve controlValve2 = ctrlValveMapper.selectControlValveByRoomNoLock(roomNo);
                if (controlValve != null) {
                    //集中器ID
                    controlRecords.setField4(controlValve.getEid());
                    //设备ID（计量点ID）
                    controlRecords.setNodeId(controlValve.getMeternum());
                    //所属厂家
                    controlRecords.setManufactor(controlValve.getManufactor());
                    //操作房间
                    controlRecords.setRoom(roomInfo.getCommunityName() + "-" + roomInfo.getBuildingName() + "-" + roomInfo.getUnitName() + "-" + roomInfo.getHouseNumber());
                } else if (controlValve2 != null) {
                    //集中器ID
                    controlRecords.setField4(controlValve2.getEid());
                    //设备ID（计量点ID）
                    controlRecords.setNodeId(controlValve2.getMeternum());
                    //所属厂家
                    controlRecords.setManufactor(controlValve2.getManufactor());
                    //操作房间
                    controlRecords.setRoom(roomInfo.getCommunityName() + "-" + roomInfo.getBuildingName() + "-" + roomInfo.getUnitName() + "-" + roomInfo.getHouseNumber());
                } else {
                    ControlValve controlValve1 = ctrlValveMapper.selectControlValveByRoomNoUnit(roomNo);
                    if (controlValve1 != null) {
                        //集中器ID
                        controlRecords.setField4(controlValve1.getEid());
                        //设备ID（计量点ID）
                        controlRecords.setNodeId(controlValve1.getMeternum());
                        //所属厂家
                        controlRecords.setManufactor("0");
                    } else {
                        throw new ServiceException("未检测到该房间或单元下的阀门，无法进行调控！");
                    }
                    //操作房间
                    controlRecords.setRoom(controlValve1.getVillageName() + "-" + controlValve1.getBuildingName() + "-" + controlValve1.getUnitName() + "单元");

                }
                //操作类型
                controlRecords.setType(type);
                //开度值
                controlRecords.setField2(handSendDto.getValue());
                //操作内容
                controlRecords.setContent("将设备进行阀门开度设置操作");
                //操作码
                controlRecords.setCode("");
                //操作结果
//                controlRecords.setField1("成功");
                //操作时间
                controlRecords.setCreateTime(new Date());
                //操作人
                controlRecords.setCreateBy(username);
                //调控类型
                controlRecords.setField5("0");
                //操作用户ID
                controlRecords.setDeptId(SecurityUtils.getUserId());

                controlRecordsMapper.insertControlRecords(controlRecords);
            }


            //阀门开度调大
        } else if (type.equals("5")) {
            for (String roomNo : roomNos) {

                ControlRecords controlRecords = new ControlRecords();
                RoomInfo roomInfo = roomInfoMapper.selectRoomInfoByRoomNo(roomNo);
                ControlValve controlValve = ctrlValveMapper.selectControlValveByRoomNoFlow(roomNo);
                if (controlValve != null) {
                    //集中器ID
                    controlRecords.setField4(controlValve.getEid());
                    //设备ID（计量点ID）
                    controlRecords.setNodeId(controlValve.getMeternum());
                    //所属厂家
                    controlRecords.setManufactor(controlValve.getManufactor());
                    //操作房间
                    controlRecords.setRoom(roomInfo.getCommunityName() + "-" + roomInfo.getBuildingName() + "-" + roomInfo.getUnitName() + "-" + roomInfo.getHouseNumber());
                } else {
                    ControlValve controlValve1 = ctrlValveMapper.selectControlValveByRoomNoUnit(roomNo);
                    if (controlValve1 != null) {
                        //集中器ID
                        controlRecords.setField4(controlValve1.getEid());
                        //设备ID（计量点ID）
                        controlRecords.setNodeId("01");
                        //所属厂家
                        controlRecords.setManufactor("0");
                    } else {
                        throw new ServiceException("未检测到该房间或单元下的阀门，无法进行调控！");
                    }
                    //操作房间
                    controlRecords.setRoom(controlValve1.getVillageName() + "-" + controlValve1.getBuildingName() + "-" + controlValve1.getUnitName() + "单元");
                    //设备ID（计量点ID）
                    controlRecords.setNodeId("01");
                    //所属厂家
                    controlRecords.setManufactor("0");
                }
                //操作类型
                controlRecords.setType(type);
                //百分比值
                controlRecords.setField3(handSendDto.getBig());

                //操作内容
                controlRecords.setContent("将设备进行阀门开度调大操作");
                //操作码
                controlRecords.setCode("");
                //操作结果
//                controlRecords.setField1("成功");
                //操作时间
                controlRecords.setCreateTime(new Date());
                //操作人
                controlRecords.setCreateBy(username);
                //调控类型
                controlRecords.setField5("0");
                //操作用户ID
                controlRecords.setDeptId(SecurityUtils.getUserId());

                controlRecordsMapper.insertControlRecords(controlRecords);
            }

            //阀门开度调小
        } else if (type.equals("6")) {
            for (String roomNo : roomNos) {

                ControlRecords controlRecords = new ControlRecords();
                RoomInfo roomInfo = roomInfoMapper.selectRoomInfoByRoomNo(roomNo);
                ControlValve controlValve = ctrlValveMapper.selectControlValveByRoomNoFlow(roomNo);
                if (controlValve != null) {
                    //集中器ID
                    controlRecords.setField4(controlValve.getEid());
                    //设备ID（计量点ID）
                    controlRecords.setNodeId(controlValve.getMeternum());
                    //所属厂家
                    controlRecords.setManufactor(controlValve.getManufactor());
                    //操作房间
                    controlRecords.setRoom(roomInfo.getCommunityName() + "-" + roomInfo.getBuildingName() + "-" + roomInfo.getUnitName() + "-" + roomInfo.getHouseNumber());
                } else {
                    ControlValve controlValve1 = ctrlValveMapper.selectControlValveByRoomNoUnit(roomNo);
                    if (controlValve1 != null) {
                        //集中器ID
                        controlRecords.setField4(controlValve1.getEid());
                        //设备ID（计量点ID）
                        controlRecords.setNodeId("01");
                        //所属厂家
                        controlRecords.setManufactor("0");
                    } else {
                        throw new ServiceException("未检测到该房间或单元下的阀门，无法进行调控！");
                    }
                    //操作房间
                    controlRecords.setRoom(controlValve1.getVillageName() + "-" + controlValve1.getBuildingName() + "-" + controlValve1.getUnitName() + "单元");
                    //设备ID（计量点ID）
                    controlRecords.setNodeId("01");
                    //所属厂家
                    controlRecords.setManufactor("0");
                }
                //操作类型
                controlRecords.setType(type);
                //百分比值
                controlRecords.setField3(handSendDto.getBig());

                //操作内容
                controlRecords.setContent("将设备进行阀门开度调小操作");
                //操作码
                controlRecords.setCode("");
                //操作结果
//                controlRecords.setField1("成功");
                //操作时间
                controlRecords.setCreateTime(new Date());
                //操作人
                controlRecords.setCreateBy(username);
                //调控类型
                controlRecords.setField5("0");
                //操作用户ID
                controlRecords.setDeptId(SecurityUtils.getUserId());

                controlRecordsMapper.insertControlRecords(controlRecords);
            }
        }
    }
@Autowired
private TemperatureControlMapper temperatureControlMapper;
    /**
     * 定时拉取天罡系统关于安悦佳苑的阀门数据
     * @return
     */
    @Override
    public Object selectControlValveLists() {
        //获取token值
        String token = getToken();
        if (token != null) {
            String url = "http://yun.plou.cn:17608/extends/userRunningData/getValveDataNow";
            String requestBody = "{\"type\": \"all\", \"page\": \"1\", \"pageSize\": \"2000\"}";

            HttpHeaders headers = new HttpHeaders();
            headers.setContentType(MediaType.APPLICATION_JSON);
            headers.set("charset", "UTF-8");
            headers.set("access_token", token);
            headers.set("client_id", "baodingfatouInterface");

            HttpEntity<String> entity = new HttpEntity<>(requestBody, headers);

            ResponseEntity<String> response = restTemplate.postForEntity(url, entity, String.class);

            try {
                ObjectMapper mapper = new ObjectMapper();
                JsonNode dataNode = mapper.readTree(response.getBody()).get("data");

                for (JsonNode node : dataNode) {
                   ControlValve controlValve=new ControlValve();
                    DateFormat df = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
                    String sysReadTime = node.get("sysReadTime").asText();
                    if (!sysReadTime.isEmpty()){
                        Date parse = df.parse(sysReadTime);
                        controlValve.setTime(parse);//上传时间
                    }
                    String address2nd = node.get("address2nd").asText();
                    controlValve.setCodes(address2nd);//设备ID
                    JsonNode opennessNode = node.get("openness");
                    if (opennessNode.isNull()) {//读取阀门数据失败 则不操作
                        System.err.println("阀门读取失败！");
                    }else {
                        controlValve.setValveangle(String.valueOf(node.get("openness").asDouble()));// 开度 0--100
//                    controlValve.setCountWork(node.get("locks").asInt());// 锁定/解锁状态--0未锁定--1锁定
//                    controlValve.setCountWork(node.get("open_status").asInt());// 阀门开关状态：--0全开--1全关--2半开--3开--4关--5未知
                        TemperatureControl temperatureControl=temperatureControlMapper.selectTemperatureControlByCode(address2nd);
                        RoomInfo roomInfo = roomInfoMapper.selectRoomInfoByRoomNo(temperatureControl.getRoomNo());
                        if (roomInfo!=null&&!temperatureControl.getDeviceType().equals("2")){//不是单元阀
                            //给采集的信息赋予相关基础信息（小区、楼栋、房间信息等）
                            //计量点ID
                            controlValve.setMeternum(temperatureControl.getNodeId());
                            //集中器ID
                            controlValve.setNodeId(temperatureControl.getFocusId());
                            controlValve.setRoomNo(temperatureControl.getRoomNo());
                            controlValve.setVillageName(temperatureControl.getCommunityName());
                            controlValve.setBuildingName(temperatureControl.getBuildingName());
                            controlValve.setUnitName(temperatureControl.getUnitName());
                            controlValve.setRoomName(temperatureControl.getRoomAme());
                            controlValve.setUserCode(roomInfo.getPersonName());
                            controlValve.setTelephone(roomInfo.getPhone());
                            controlValve.setRoomType("其他");
                            controlValve.setLocation(temperatureControl.getInstall());
//            controlValve.setUploadtime(new Date());
                            controlValve.setManufactor("2");
                            controlValve.setCreateTime(new Date());
//            controlValve.setDeviceStatus("正常");//todo 判断设备状态是否正常（未定）
//            controlValve.setDeviceState("正常");//todo  判断维修状态是否正常（未定）
//            controlValve.setRoomState("正常");
                            controlValve.setState("0");
                            controlValve.setHistory("1");
                            //todo 将该表的表类型进行赋值
                            controlValve.setType(temperatureControl.getDeviceType());
                        }else {
                            //给采集的信息赋予相关基础信息（小区、楼栋、房间信息等）
                            //计量点ID
                            controlValve.setMeternum(temperatureControl.getNodeId());
                            //集中器ID
                            controlValve.setNodeId(temperatureControl.getFocusId());
                            controlValve.setRoomNo(temperatureControl.getRoomNo());
                            controlValve.setVillageName(temperatureControl.getCommunityName());
                            controlValve.setBuildingName(temperatureControl.getBuildingName());
                            controlValve.setUnitName(temperatureControl.getUnitName());
                            controlValve.setRoomName(temperatureControl.getRoomAme());
                            controlValve.setRoomType("其他");
                            controlValve.setLocation(temperatureControl.getInstall());
//            controlValve.setUploadtime(new Date());
                            controlValve.setManufactor("2");
                            controlValve.setCreateTime(new Date());
//            controlValve.setDeviceStatus("正常");//todo 判断设备状态是否正常（未定）
//            controlValve.setDeviceState("正常");//todo  判断维修状态是否正常（未定）
//            controlValve.setRoomState("正常");
                            controlValve.setState("0");
                            controlValve.setHistory("1");
                            //todo 将该表的表类型进行赋值
                            controlValve.setType(temperatureControl.getDeviceType());

                        }
                        //将最新数据存储前，将表中现有数据更改为历史数据
                        ControlValve controlValve1= controlValveMapper.selectControlValveByRoomNoType(controlValve.getRoomNo(),controlValve.getType());
                        if (controlValve1!=null){
                            //将此数据更改为历史数据
                            controlValveMapper.updateControlValveHistory(controlValve1.getId());
                        }
                        // 将数据存入数据库
                        controlValveMapper.insertControlValve(controlValve);
                    }

                }
                return dataNode.toString();
            } catch (Exception e) {
                e.printStackTrace();
            }
        }
        return null;
    }


    private final RestTemplate restTemplate = new RestTemplate();
    private String getToken() {
        String tokenUrl = "http://yun.plou.cn/module/oauth/token";
        String params = "?grant_type=client_credentials&client_id=baodingfatouInterface&client_secret=baodingfatouInterface123!";

        ResponseEntity<String> response = restTemplate.getForEntity(tokenUrl + params, String.class);

        try {
            ObjectMapper mapper = new ObjectMapper();
            JsonNode rootNode = mapper.readTree(response.getBody());
            System.err.println(rootNode.path("data").path("access_token").asText());
            return rootNode.path("data").path("access_token").asText();

        } catch (Exception e) {
            e.printStackTrace();
            return null;
        }
    }

    /**
     * 定时拉取天罡系统关于厚福盈的阀门数据（锁闭阀）
     * @return
     */
    @Override
    public Object selectControlValveListss() {
        //获取token
        String tokens = getTokens();
        //获取当前年份
        Calendar calendar = Calendar.getInstance();
        int year = calendar.get(Calendar.YEAR);
        int year1 = calendar.get(Calendar.YEAR)+1;
        String string = String.valueOf(year);
        String string1 = String.valueOf(year1);
        String string2 = string + "-" + string1;

        String url = "http://39.99.245.90:8020/jeecgboot/meter/mrTempValveData/api/list";

        HttpHeaders headers = new HttpHeaders();
        headers.set("appKey", "2c9a8384932421d901932421d9110000");
        headers.set("appSecret", "2c9a8384932421d901932421d91100012c9a8384932421d901932421d9110002");
        headers.set("appToken", tokens);

        HttpEntity<String> entity = new HttpEntity<>(headers);

        ResponseEntity<String> response = restTemplate.exchange(
                url + "?pageNo=1&pageSize=100&heatingYear="+string2+"&dateType=1",
                HttpMethod.GET,
                entity,
                String.class
        );


        String responseBody = response.getBody();
        ObjectMapper objectMapper = new ObjectMapper();

        try {
            JsonNode rootNode = objectMapper.readTree(responseBody);
            JsonNode recordsNode = rootNode.path("result").path("records");

            for (JsonNode record : recordsNode) {
                ControlValve controlValve=new ControlValve();
                // 对每个记录进行操作
                // 温控阀地址码(设备编号) 95105925
                String tempValveNo = record.path("tempValveNo").asText();
                controlValve.setCodes(tempValveNo);
                // 当前用热状态  供热/报停/强停/退网
                String heatingStateDictText = record.path("heatingState_dictText").asText();
                controlValve.setField3(heatingStateDictText);
                // 抄表时间
                DateFormat df = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
                String readingTime = record.path("readingTime").asText();
                if (!readingTime.isEmpty()){
                    Date parse = df.parse(readingTime);
                    controlValve.setTime(parse);//上传时间
                }
                // 阀门开关状态 阀门开关状态（开阀:1，关阀:2，强制开阀:3，强制关阀:4，自由控制:5，
                //开阀（锁定）:6，关阀（锁定）:7，开度控制:8	，异常:9	，强制控阀:10，未开户:11，电池欠压:12，阀门断电:13）
                String valveStatus = record.path("valveStatus").asText();
                if (valveStatus.equals("3")){
                    controlValve.setValveangle("100");
                }else if (valveStatus.equals("4")){
                    controlValve.setValveangle("0");
                }else {
                    controlValve.setValveangle("--");
                }
                TemperatureControl temperatureControl=temperatureControlMapper.selectTemperatureControlByCode(tempValveNo);
                RoomInfo roomInfo = roomInfoMapper.selectRoomInfoByRoomNo(temperatureControl.getRoomNo());
                if (roomInfo!=null&&!temperatureControl.getDeviceType().equals("2")){//不是单元阀
                    //给采集的信息赋予相关基础信息（小区、楼栋、房间信息等）
                    //计量点ID
                    controlValve.setMeternum(temperatureControl.getNodeId());
                    //集中器ID
                    controlValve.setNodeId(temperatureControl.getFocusId());
                    controlValve.setRoomNo(temperatureControl.getRoomNo());
                    controlValve.setVillageName(temperatureControl.getCommunityName());
                    controlValve.setBuildingName(temperatureControl.getBuildingName());
                    controlValve.setUnitName(temperatureControl.getUnitName());
                    controlValve.setRoomName(temperatureControl.getRoomAme());
                    controlValve.setUserCode(roomInfo.getPersonName());
                    controlValve.setTelephone(roomInfo.getPhone());
                    controlValve.setRoomType("其他");
                    controlValve.setLocation(temperatureControl.getInstall());
//            controlValve.setUploadtime(new Date());
                    controlValve.setManufactor("2");
                    controlValve.setCreateTime(new Date());
//            controlValve.setDeviceStatus("正常");//todo 判断设备状态是否正常（未定）
//            controlValve.setDeviceState("正常");//todo  判断维修状态是否正常（未定）
//            controlValve.setRoomState("正常");
                    controlValve.setState("0");
                    controlValve.setHistory("1");
                    //todo 将该表的表类型进行赋值
                    controlValve.setType(temperatureControl.getDeviceType());
                }else {
                    //给采集的信息赋予相关基础信息（小区、楼栋、房间信息等）
                    //计量点ID
                    controlValve.setMeternum(temperatureControl.getNodeId());
                    //集中器ID
                    controlValve.setNodeId(temperatureControl.getFocusId());
                    controlValve.setRoomNo(temperatureControl.getRoomNo());
                    controlValve.setVillageName(temperatureControl.getCommunityName());
                    controlValve.setBuildingName(temperatureControl.getBuildingName());
                    controlValve.setUnitName(temperatureControl.getUnitName());
                    controlValve.setRoomName(temperatureControl.getRoomAme());
                    controlValve.setRoomType("其他");
                    controlValve.setLocation(temperatureControl.getInstall());
//            controlValve.setUploadtime(new Date());
                    controlValve.setManufactor("2");
                    controlValve.setCreateTime(new Date());
//            controlValve.setDeviceStatus("正常");//todo 判断设备状态是否正常（未定）
//            controlValve.setDeviceState("正常");//todo  判断维修状态是否正常（未定）
//            controlValve.setRoomState("正常");
                    controlValve.setState("0");
                    controlValve.setHistory("1");
                    //todo 将该表的表类型进行赋值
                    controlValve.setType(temperatureControl.getDeviceType());

                }
                //将最新数据存储前，将表中现有数据更改为历史数据
                ControlValve controlValve1= controlValveMapper.selectControlValveByRoomNoType(controlValve.getRoomNo(),controlValve.getType());
                if (controlValve1!=null){
                    //将此数据更改为历史数据
                    controlValveMapper.updateControlValveHistory(controlValve1.getId());
                }
                // 将数据存入数据库
                controlValveMapper.insertControlValve(controlValve);

                // 安装位置 厚福盈 06-03-101
//                String houseAddress = record.path("houseAddress").asText();
                // 温控阀类型  天罡TICV
//                String deviceTypeName = record.path("deviceTypeName").asText();
                // 用户编码
//                String heatingCardNo = record.path("heatingCardNo").asText();
                // 采暖面积
//                String areaCN = record.path("areaCN").asText();
                // 建筑面积
//                String areaJZ = record.path("areaJZ").asText();
                // 阀门开关次数
//                String switchingTimes = record.path("switchingTimes").asText();
                // 累计开阀时间(m)
//                String openingTime = record.path("openingTime").asText();
                // 设定温度(℃)
//                String settingTemp = record.path("settingTemp").asText();
                // 平均室温(℃)
//                String averageTemp = record.path("averageTemp").asText();
                // 当前室温(℃)
//                String currentTemp = record.path("currentTemp").asText();
                // 供水温度(℃)
//                String waterTemp = record.path("waterTemp").asText();
                // 回水温度(℃)
//                String rwaterTemp = record.path("rwaterTemp").asText();
                // 温差(℃)
//                String waterTempDiffer = record.path("waterTempDiffer").asText();
                // 累计热量(kWh)
//                String accumulatedHeat = record.path("accumulatedHeat").asText();
                // 累积工作时间(m)
//                String operatingTime = record.path("operatingTime").asText();
                // 抄表结果 （抄表失败/抄表成功）
//                String dataUploadStatusDictText = record.path("dataUploadStatus_dictText").asText();
                // 报警  无报警
//                String warningTypeIdDictText = record.path("warningTypeId_dictText").asText();
                // 客户名称
//                String customerName = record.path("customerName").asText();
                // 抄表方式  自动采集/手动采集/手工添加/批量导入/更换添加/数据调整导入
//                String readingTypeDictText = record.path("readingType_dictText").asText();
                // 阀门分类  户阀/单元阀
//                String valveClassDictText = record.path("valveClass_dictText").asText();
                // 区域类型
//                String areaType = record.path("areaType").asText();
                // 所属单元阀地址码
//                String unitTempValveNo = record.path("unitTempValveNo").asText();


                // 处理逻辑(数据持久化)

            }
        } catch (IOException | ParseException e) {
            e.printStackTrace();
        }
        return responseBody;
    }

    /**
     * 定时拉取天罡系统关于小察院和防疫站的阀门数据（平衡阀）
     * @return
     */
    @Override
    public Object selectControlValveListsss() {
        //获取token
        String tokens = getTokens();
        //获取当前年份
        Calendar calendar = Calendar.getInstance();
        int year = calendar.get(Calendar.YEAR);
        int year1 = calendar.get(Calendar.YEAR)+1;
        String string = String.valueOf(year);
        String string1 = String.valueOf(year1);
        String string2 = string + "-" + string1;

        String url = "http://39.99.245.90:8020/jeecgboot/meter/mrBalanceTempData/api/list";

        HttpHeaders headers = new HttpHeaders();
        headers.set("appKey", "2c9a8384932421d901932421d9110000");
        headers.set("appSecret", "2c9a8384932421d901932421d91100012c9a8384932421d901932421d9110002");
        headers.set("appToken", tokens);

        HttpEntity<String> entity = new HttpEntity<>(headers);

        ResponseEntity<String> response = restTemplate.exchange(
                url + "?pageNo=1&pageSize=200&heatingYear="+string2+"&dateType=1",
                HttpMethod.GET,
                entity,
                String.class
        );


        String responseBody = response.getBody();
        ObjectMapper objectMapper = new ObjectMapper();
        try {
            JsonNode rootNode = objectMapper.readTree(responseBody);
            JsonNode recordsNode = rootNode.path("result").path("records");

            for (JsonNode record : recordsNode) {
                ControlValve controlValve=new ControlValve();
                // 对每个记录进行操作
                // 温控阀地址码(设备编号) 95105925
                String tempValveNo = record.path("balanceTempNo").asText();
                controlValve.setCodes(tempValveNo);
                // 当前用热状态  供热/报停/强停/退网
                String heatingStateDictText = record.path("heatingState_dictText").asText();
                controlValve.setField3(heatingStateDictText);
                // 抄表时间
                DateFormat df = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
                String readingTime = record.path("readingTime").asText();
                if (!readingTime.isEmpty()){
                    Date parse = df.parse(readingTime);
                    controlValve.setTime(parse);//上传时间
                }
                // 阀门开度
                String valveStatus = record.path("tempOpenDegree").asText();
                controlValve.setValveangle(valveStatus);
                //进水温度
                String waterTemp = record.path("waterTemp").asText();
                controlValve.setIntemp(waterTemp);
                //回水温度
                String rwaterTemp = record.path("rwaterTemp").asText();
                controlValve.setOuttemp(rwaterTemp);
                //累积开阀时间
                String openingTime = record.path("openingTime").asText();
                controlValve.setOpentime(openingTime);
                TemperatureControl temperatureControl=temperatureControlMapper.selectTemperatureControlByCode(tempValveNo);
                RoomInfo roomInfo = roomInfoMapper.selectRoomInfoByRoomNo(temperatureControl.getRoomNo());
                if (roomInfo!=null&&!temperatureControl.getDeviceType().equals("2")){//不是单元阀
                    //给采集的信息赋予相关基础信息（小区、楼栋、房间信息等）
                    //计量点ID
                    controlValve.setMeternum(temperatureControl.getNodeId());
                    //集中器ID
                    controlValve.setNodeId(temperatureControl.getFocusId());
                    controlValve.setRoomNo(temperatureControl.getRoomNo());
                    controlValve.setVillageName(temperatureControl.getCommunityName());
                    controlValve.setBuildingName(temperatureControl.getBuildingName());
                    controlValve.setUnitName(temperatureControl.getUnitName());
                    controlValve.setRoomName(temperatureControl.getRoomAme());
                    controlValve.setUserCode(roomInfo.getPersonName());
                    controlValve.setTelephone(roomInfo.getPhone());
                    controlValve.setRoomType("其他");
                    controlValve.setLocation(temperatureControl.getInstall());
//            controlValve.setUploadtime(new Date());
                    controlValve.setManufactor("2");
                    controlValve.setCreateTime(new Date());
//            controlValve.setDeviceStatus("正常");//todo 判断设备状态是否正常（未定）
//            controlValve.setDeviceState("正常");//todo  判断维修状态是否正常（未定）
//            controlValve.setRoomState("正常");
                    controlValve.setState("0");
                    controlValve.setHistory("1");
                    //todo 将该表的表类型进行赋值
                    controlValve.setType(temperatureControl.getDeviceType());
                }else {
                    //给采集的信息赋予相关基础信息（小区、楼栋、房间信息等）
                    //计量点ID
                    controlValve.setMeternum(temperatureControl.getNodeId());
                    //集中器ID
                    controlValve.setNodeId(temperatureControl.getFocusId());
                    controlValve.setRoomNo(temperatureControl.getRoomNo());
                    controlValve.setVillageName(temperatureControl.getCommunityName());
                    controlValve.setBuildingName(temperatureControl.getBuildingName());
                    controlValve.setUnitName(temperatureControl.getUnitName());
                    controlValve.setRoomName(temperatureControl.getRoomAme());
                    controlValve.setRoomType("其他");
                    controlValve.setLocation(temperatureControl.getInstall());
//            controlValve.setUploadtime(new Date());
                    controlValve.setManufactor("2");
                    controlValve.setCreateTime(new Date());
//            controlValve.setDeviceStatus("正常");//todo 判断设备状态是否正常（未定）
//            controlValve.setDeviceState("正常");//todo  判断维修状态是否正常（未定）
//            controlValve.setRoomState("正常");
                    controlValve.setState("0");
                    controlValve.setHistory("1");
                    //todo 将该表的表类型进行赋值
                    controlValve.setType(temperatureControl.getDeviceType());

                }
                //将最新数据存储前，将表中现有数据更改为历史数据
                ControlValve controlValve1= controlValveMapper.selectControlValveByRoomNoType(controlValve.getRoomNo(),controlValve.getType());
                if (controlValve1!=null){
                    //将此数据更改为历史数据
                    controlValveMapper.updateControlValveHistory(controlValve1.getId());
                }
                // 将数据存入数据库
                controlValveMapper.insertControlValve(controlValve);


            }
        } catch (IOException | ParseException e) {
            e.printStackTrace();
        }

        return responseBody;
    }

    /**
     * 获取关于小察院、厚福防疫站小区的token
     * @return
     */
    private String getTokens() {
        String tokenUrl = "http://39.99.245.90:8020//jeecgboot/sys/authorizationInfor/genarateToken";
        String params = "?appKey=2c9a8384932421d901932421d9110000&appSecret=2c9a8384932421d901932421d91100012c9a8384932421d901932421d9110002";

        ResponseEntity<String> response = restTemplate.getForEntity(tokenUrl + params, String.class);

        try {
            ObjectMapper mapper = new ObjectMapper();
            JsonNode rootNode = mapper.readTree(response.getBody());
            System.err.println(rootNode.path("result").path("appToken").asText());
            return rootNode.path("result").path("appToken").asText();

        } catch (Exception e) {
            e.printStackTrace();
            return null;
        }
    }


    public static void main(String[] args) {
//        String decimalString = "85";
//        String bcdString = convertToBCD(decimalString);
//        System.out.println("BCD representation of " + decimalString + ": " + bcdString);
//        String tokenUrl = "http://39.99.245.90:8020//jeecgboot/sys/authorizationInfor/genarateToken";
//        String params = "?appKey=2c9a8384932421d901932421d9110000&appSecret=2c9a8384932421d901932421d91100012c9a8384932421d901932421d9110002";
//
//        ResponseEntity<String> response = restTemplate.getForEntity(tokenUrl + params, String.class);
//
//        try {
//            ObjectMapper mapper = new ObjectMapper();
//            JsonNode rootNode = mapper.readTree(response.getBody());
//            System.err.println(rootNode.path("result").path("appToken").asText());
//
//        } catch (Exception e) {
//            e.printStackTrace();
//        }

        Calendar calendar = Calendar.getInstance();
        int year = calendar.get(Calendar.YEAR);
        int year1 = calendar.get(Calendar.YEAR)+1;
        String string = String.valueOf(year);
        String string1 = String.valueOf(year1);
        String string2 = string + "-" + string1;
        System.err.println(string2);

    }

}
